import type { Metadata } from 'next';
import React from 'react';
import Layout from '@/components/Layout';
import { getServerSideCategories } from '@/services/back';
import { tryParse } from '@/utils/common';
import { getCookie, getIsLogin, Logger } from '@/utils/back';
import { GoogleAnalytics, GoogleTagManager } from '@next/third-parties/google';

const logger = Logger('server-layout');

const isProd = process.env.NEXT_PUBLIC_APP_ENV === 'production';

export const metadata: Metadata = {
  applicationName: 'my-company',
  creator: 'my-brand',
  title: 'my-company',
  description:
    "",
  keywords: [],
  icons: {
   
  },
  robots: {
    index: isProd,
    follow: isProd,
    nocache: false,
  },
};

function correctCategoryDescription(categories: Category[]) {
  categories.forEach(category => {
    const desc = category.description || '';
    const description = desc
      .replace(
        /^(\r|\n|\r\n)*"*(\r|\n|\r\n)*|(\r|\n|\r\n)*"*(\r|\n|\r\n)*$/g,
        ''
      )
      .replace(/""/g, '"');
    category.description = description;
  });
}
export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  // logger.info('layout component render..');

  const isLogin = getIsLogin();
  const token = getCookie('token');
  const token_ctime = getCookie('token_ctime');
  const userInfo = token ? tryParse(atob(token.split('.')[1])) : {};

  const catgories = await getServerSideCategories();
  correctCategoryDescription(catgories);

  return (
    <html lang="en">
      <body>
        <Layout serverData={{ catgories, isLogin, userInfo, token_ctime }}>
          {children}
        </Layout>
        <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GAID || ''} />
        <GoogleAnalytics gaId={process.env.NEXT_PUBLIC_GAID_COMBINED || ''} />
        <GoogleTagManager gtmId="GTM-TG9QN6M4" />
        <GoogleTagManager gtmId="GTM-THF29CL" />
      </body>
    </html>
  );
}
